package cn.iotnc.camera.util

import android.content.Context
import android.net.wifi.WifiManager

private fun Context.wifiManager() =
    applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

fun Context.gateWay() = try {
    val dhcpInfo = wifiManager().dhcpInfo
    dhcpInfo.gateway.toStringIp()
} catch (e: Exception) {
    e.message ?: "未知错误"
}

fun Context.ip() = try {
    val wifiInfo = wifiManager().connectionInfo
    wifiInfo.ipAddress.toStringIp()
} catch (e: Exception) {
    e.message ?: "未知错误"
}

fun Context.netMask() = try {
    val dhcpInfo = wifiManager().dhcpInfo
    dhcpInfo.netmask.toStringIp()
} catch (e: Exception) {
    e.message ?: "未知错误"
}

private fun Int.toStringIp() = StringBuilder()
    .append(this and 0xFF).append(".")
    .append(this shr 8 and 0xFF).append(".")
    .append(this shr 16 and 0xFF).append(".")
    .append(this shr 24 and 0xFF).toString()
